<template>
  <view class="mt-more-column-checkbox">
    <mt-popup ref="popupRef" :title="title" :top-confirm="false" close-on-click-overlay show-footer @reset="handleReset" @confirm="handleConfirm">
      <view class="mt-more-checkbox_content">
        <view v-if="showCheckName && checkResultName.length" class="checked-box">
          <text class="text-28rpx text-#1C213E pt-8rpx">当前选择：</text>
          <view class="content">
            <text v-for="(item, index) in checkResultName.slice(0, 3)" :key="item" class="tag">
              {{ index > 1 ? '...+' + (checkResultName.length - index) : item }}
            </text>
          </view>
        </view>
        <view class="mt-more-checkbox_scroll" :style="{ 'padding-top': showCheckName && checkResultName.length ? 0 : '30rpx' }">
          <view class="w-50%">
            <scroll-view class="scroll-view first" scroll-y>
              <view v-for="(item, index) in firstList" :key="item[value]" class="scroll-li" :class="{ active: currentFirst === index }">
                <view class="scroll-li_content" @click="handleChangeFirstExpend(index)">
                  <view class="txt">
                    <slot name="first" :row="item" :index="index">
                      <text>{{ item[label] }}</text>
                    </slot>
                  </view>
                  <view class="w-32rpx h-32rpx" @click.stop="handleChangeFirstCheck(item, index)">
                    <image
                      v-if="item._checked === 'no-select'"
                      class="w-32rpx h-32rpx"
                      src="https://mingtu-resources.oss-cn-shenzhen.aliyuncs.com/mtym-app-assets/icon-checkbox.svg"
                    ></image>
                    <image
                      v-if="item._checked === 'selected'"
                      class="w-32rpx h-32rpx"
                      src="https://mingtu-resources.oss-cn-shenzhen.aliyuncs.com/mtym-app-assets/icon-checkbox-select.svg"
                    ></image>
                    <image
                      v-if="item._checked === 'half-select'"
                      class="w-32rpx h-32rpx"
                      src="https://mingtu-resources.oss-cn-shenzhen.aliyuncs.com/mtym-app-assets/icon-checkbox-half-select.svg"
                    ></image>
                  </view>
                </view>
              </view>
            </scroll-view>
          </view>
          <view class="w-50%">
            <scroll-view class="scroll-view two" scroll-y>
              <view v-for="(item, index) in firstList[currentFirst][child]" :key="item[value]" class="scroll-li">
                <view class="scroll-li_content">
                  <view class="txt">
                    <slot name="two" :row="item" :index="index">
                      <text>{{ item[label] }}</text>
                    </slot>
                  </view>
                  <view class="w-32rpx h-32rpx" @click.stop="handleChangeTwoCheck(item, index)">
                    <image
                      v-if="item._checked === 'no-select'"
                      class="w-32rpx h-32rpx"
                      src="https://mingtu-resources.oss-cn-shenzhen.aliyuncs.com/mtym-app-assets/icon-checkbox.svg"
                    ></image>
                    <image
                      v-if="item._checked === 'selected'"
                      class="w-32rpx h-32rpx"
                      src="https://mingtu-resources.oss-cn-shenzhen.aliyuncs.com/mtym-app-assets/icon-checkbox-select.svg"
                    ></image>
                  </view>
                </view>
              </view>
            </scroll-view>
          </view>
        </view>
      </view>
    </mt-popup>
  </view>
</template>

<script setup>
const props = defineProps({
  list: {
    type: Array,
    default: () => []
  },
  title: {
    type: String,
    default: '选择产品类别'
  },
  label: {
    type: String,
    default: 'name'
  },
  value: {
    type: String,
    default: 'id'
  },
  child: {
    type: String,
    default: 'children'
  },
  confirmClose: {
    type: Boolean,
    default: true
  },
  showCheckName: {
    type: Boolean,
    default: false
  }
});

const emits = defineEmits(['confirm']);

const firstList = ref([]);
const currentFirst = ref(0);

watch(
  () => props.list,
  (newVal) => {
    if (newVal && newVal.length) {
      let arr = JSON.parse(JSON.stringify(newVal));

      firstList.value = arr;
      currentFirst.value = 0;
    } else {
      firstList.value = [];
      currentFirst.value = 0;
    }
  },
  { immediate: true }
);
// 最终选择的数据 value
const checkResultId = defineModel({ type: Array });
// 最终选择的数据，最后一层的 name
const checkResultName = ref([]);

function handleChangeFirstExpend(index) {
  currentFirst.value = index;
}

function returnCheck(_checked) {
  const bols = _checked === 'selected' || _checked === 'half-select';
  const res = bols ? 'no-select' : 'selected';
  return res;
}
function handleChangeFirstCheck(item, index) {
  const nesItem = JSON.parse(JSON.stringify(item));

  nesItem._checked = returnCheck(item._checked);
  for (const son of nesItem[props.child]) {
    son._checked = nesItem._checked;
  }
  firstList.value[index] = nesItem;

  getSelectNode();
}

function handleChangeTwoCheck(item, index) {
  const oldChild = JSON.parse(JSON.stringify(firstList.value[currentFirst.value][props.child]));
  oldChild[index]._checked = returnCheck(item._checked);

  firstList.value[currentFirst.value][props.child] = oldChild;

  const checkArr = oldChild.filter((son) => son._checked === 'selected');

  if (checkArr.length === 0) {
    firstList.value[currentFirst.value]._checked = 'no-select';
  } else if (checkArr.length < oldChild.length) {
    firstList.value[currentFirst.value]._checked = 'half-select';
  } else if (checkArr.length === oldChild.length) {
    firstList.value[currentFirst.value]._checked = 'selected';
  }

  getSelectNode();
}

function addLevelToTree(tree, level = 1) {
  return tree.map((node) => {
    node._level = level;
    node._checked = 'no-select';
    if (node[props.child]?.length > 0) {
      node[props.child] = addLevelToTree(node[props.child], level + 1);
    } else {
      node[props.child] = null;
    }
    return node;
  });
}

function handleInitSelect(checkData, data) {
  if (!checkData || checkData.length < 2) return;
  // 第一步回显数据，父级回显是错的
  function changeCheckedFirst(arr, level = 1) {
    for (const item of arr) {
      if (item[props.child]) {
        if (checkData[level - 1].includes(item[props.value])) {
          item._checked = 'half-select';
        }
        changeCheckedFirst(item[props.child], level + 1);
      } else {
        if (checkData[level - 1].includes(item[props.value])) {
          item._checked = 'selected';
        }
      }
    }
  }
  // 第二步，根据子级回显父级
  function changeCheckedTwo(arr) {
    for (const item of arr) {
      if (item[props.child]) {
        const checkArr = item[props.child].filter((son) => son._checked === 'selected');
        if (checkArr.length === 0) {
          item._checked = 'no-select';
        } else if (checkArr.length < item[props.child].length) {
          item._checked = 'half-select';
        } else if (checkArr.length === item[props.child].length) {
          item._checked = 'selected';
        }
        changeCheckedTwo(item[props.child]);
      }
    }
  }

  changeCheckedFirst(data);
  changeCheckedTwo(data);
}

function getSelectNode() {
  const data = JSON.parse(JSON.stringify(firstList.value));
  const result = [];
  function getChecked(arr, level = 1) {
    for (const item of arr) {
      if (!result[level - 1]) {
        result[level - 1] = [];
      }
      if (item._checked !== 'no-select') {
        // result[level - 1].push({
        //   [props.label]: item[props.label],
        //   [props.value]: item[props.value]
        // });
        result[level - 1].push({
          ...item,
          [props.child]: null
        });
      }
      if (item[props.child]) {
        getChecked(item[props.child], level + 1);
      }
    }
  }
  getChecked(data);

  checkResultName.value = result[result.length - 1].map((son) => son[props.label]);

  return result;
}

const popupRef = ref();
function open() {
  let arr = JSON.parse(JSON.stringify(firstList.value));
  arr = addLevelToTree(arr);
  handleInitSelect(checkResultId.value, arr);

  firstList.value = arr;
  getSelectNode();

  popupRef.value.open();
}

function close() {
  popupRef.value.close();
}

function handleReset() {
  let arr = JSON.parse(JSON.stringify(firstList.value));
  arr = addLevelToTree(arr);
  firstList.value = arr;
}

function handleConfirm() {
  const result = getSelectNode();
  const valueArray = result.map((row) => row.map((obj) => obj[props.value]));

  checkResultId.value = valueArray;

  emits('confirm', valueArray, result);

  if (props.confirmClose) {
    close();
  }
}

defineExpose({
  open,
  close
});
</script>

<style lang="scss" scoped>
.mt-more-checkbox_content {
  border-top: 2rpx solid #f3f3f3;
  .checked-box {
    display: flex;
    align-items: flex-start;
    padding: 40rpx 32rpx;
    .content {
      flex: 1;
      min-width: 0;
      white-space: nowrap;
      overflow: hidden;
      .tag {
        display: inline-block;
        font-size: 28rpx;
        color: #1c213e;
        padding: 8rpx 16rpx;
        margin-left: 16rpx;
        background-color: #f5f5f5;
        border-radius: 4rpx;
      }
    }
  }
  .mt-more-checkbox_scroll {
    display: flex;
    padding: 0 32rpx;
    .scroll-view {
      height: 600rpx;
      &.first {
        .scroll-li.active {
          background-color: #f9f9f9;
        }
      }
      &.two {
        background-color: #f9f9f9;
      }
    }
    .scroll-li {
      padding: 0 24rpx;
      .scroll-li_content {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 30rpx 0;
        border-bottom: 2rpx solid #f3f3f3;
        .txt {
          width: 220rpx;
          font-size: 28rpx;
          color: #1c213e;
          word-break: break-all;
        }
      }
    }
  }
}
</style>
